package com.zhen.aikan.service.impl;


import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhen.aikan.entity.VodDetail;
import com.zhen.aikan.entity.VodType;
import com.zhen.aikan.mapper.VodDetailMapper;

import com.zhen.aikan.service.IVodDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.service.IVodTypeService;
import com.zhen.aikan.util.TimeUtil;
import com.zhen.aikan.vo.VodSimpleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static com.zhen.aikan.util.TimeUtil.getDayOfWeek;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lijiazhen
 * @since 2023-09-11
 */
@Service
public class VodDetailServiceImpl extends ServiceImpl<VodDetailMapper, VodDetail> implements IVodDetailService {

    @Autowired
    private IVodTypeService vodTypeService;

    @Override
    public Page<Map<String, Object>> getHotAnimationWithPage(String typeName, Integer current, Integer size) {
        //查出类型的id
        List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
        //将id添加到查询条件中
        QueryWrapper<VodDetail> detailQueryWrapper = new QueryWrapper<>();
        vodTypes.forEach(item -> {
            detailQueryWrapper.or().eq("type_id", item.getTypeId());
        });
        //按点击数来排序
        detailQueryWrapper.orderByDesc("vod_hits");

        //把查出来的vodDetil拷贝到vodSimpleVo
        Page<Map<String, Object>> myPage = baseMapper.selectMapsPage(new Page<>(current, size), detailQueryWrapper);
        List<VodSimpleVo> vodSimpleVos = new ArrayList<>();
        myPage.getRecords().forEach(item -> {
            VodSimpleVo vodSimpleVo = new VodSimpleVo();
            vodSimpleVo.setVodId((Long) item.get("vod_id"));
            vodSimpleVo.setVodLetter((String) item.get("vod_letter"));
            vodSimpleVo.setVodClass((String) item.get("vod_class"));
            vodSimpleVo.setVodName((String) item.get("vod_name"));
            vodSimpleVo.setVodPic((String) item.get("vod_pic"));
            vodSimpleVo.setVodScore((String) item.get("vod_score"));
            vodSimpleVo.setVodSerial((String) item.get("vod_serial"));
            vodSimpleVo.setVodRemarks((String) item.get("vod_remarks"));
            vodSimpleVos.add(vodSimpleVo);
        });
        Map<String, Object> vods = new HashMap<>();
        vods.put("vodSimpleVos", vodSimpleVos);
        List<Map<String, Object>> a = new ArrayList<>();
        a.add(vods);
        myPage.setRecords(a);
        return myPage;
    }

    @Override
    public VodDetail getVodDetailById(long vodId) {
        VodDetail vodDetail = baseMapper.selectOne(new QueryWrapper<VodDetail>().eq("vod_id", vodId));
        //将音频网址分割出m3u8类型的
        List<String> vodM3m8Url = new ArrayList<>();
        String vodPlayUrl = vodDetail.getVodPlayUrl();
        String[] s1 = vodPlayUrl.split("\\$\\$\\$");
        int index = 0;
        if (s1.length > 1) {
            index = 1;
        }
        String[] s2 = s1[index].split("#");
        for (int i = 0; i < s2.length; i++) {
            String[] s3 = s2[i].split("\\$");
            vodM3m8Url.add(s3[1]);
        }
        vodDetail.setM3u8Urls(vodM3m8Url);
        vodDetail.setVodPlayUrl("");
        return vodDetail;
    }

    @Override
    public Page<Map<String, Object>> getVodByCondition(Integer pTypeId, Integer sTypeId, String area, String other, Integer current, Integer size) {
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        /*
        pTypeId:0 sTypeId:0 查全部
        pTypeId>0 sTypeId:0 查父的id = pTypeId or 本id = pTypeId
        pTypeId>0 sTypeId>0 本id = sTypeId and父id = pTypeId
         */
        if (pTypeId > 0 && sTypeId == 0) {
            wrapper.eq("type_id", pTypeId).or().eq("type_pid", pTypeId);
        } else if (pTypeId > 0 && sTypeId > 0) {
            wrapper.eq("type_id", sTypeId).eq("type_pid", pTypeId);
        }
        if (StringUtils.hasText(area)) {
            wrapper.like("vod_area", area);
        }
        if (StringUtils.hasText(other)) {
            if ("最热".equals(other)) {
                wrapper.orderByDesc("vod_hits");
            } else if ("高分".equals(other)) {
                wrapper.orderByDesc("vod_score");
            }
            wrapper.orderByDesc("vod_time");
        }
        Page<Map<String, Object>> myPage = baseMapper.selectMapsPage(new Page<>(current, size), wrapper);
        List<VodSimpleVo> vodSimpleVos = new ArrayList<>();
        myPage.getRecords().forEach(item -> {
            VodSimpleVo vodSimpleVo = new VodSimpleVo();
            vodSimpleVo.setVodId((Long) item.get("vod_id"));
            vodSimpleVo.setVodLetter((String) item.get("vod_letter"));
            vodSimpleVo.setVodClass((String) item.get("vod_class"));
            vodSimpleVo.setVodName((String) item.get("vod_name"));
            vodSimpleVo.setVodPic((String) item.get("vod_pic"));
            vodSimpleVo.setVodScore((String) item.get("vod_score"));
            vodSimpleVo.setVodSerial((String) item.get("vod_serial"));
            vodSimpleVo.setVodRemarks((String) item.get("vod_remarks"));
            vodSimpleVos.add(vodSimpleVo);
        });
        Map<String, Object> vods = new HashMap<>();
        vods.put("vodSimpleVos", vodSimpleVos);
        List<Map<String, Object>> a = new ArrayList<>();
        a.add(vods);
        myPage.setRecords(a);
        return myPage;
    }

    @Override
    public Page<Map<String, Object>> getVodLeaderboardByTypeName(String typeName, Integer current, Integer size) {
        //查出动漫类型的id
        List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
        //配置查询条件
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        //获取当前月开始、结束的时间戳
        Long monthStartTime = TimeUtil.getMonthStartTime(Calendar.getInstance().getTimeInMillis(), "GMT+8:00");
        Long monthEndTime = TimeUtil.getMonthEndTime(Calendar.getInstance().getTimeInMillis(), "GMT+8:00");
        Instant instant1 = Instant.ofEpochMilli(monthStartTime);
        Instant instant2 = Instant.ofEpochMilli(monthEndTime);
        //查询当前月更新的影片
        wrapper.between("vod_time",
                LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()),
                LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()));
        //过滤出符合的类型的影片
        wrapper.and(w -> {
            vodTypes.forEach(item -> {
                w.or().eq("type_id", item.getTypeId());
            });
        });
        //根据点击量来排序
        wrapper.orderByDesc("vod_hits");

        Page<Map<String, Object>> myPage = baseMapper.selectMapsPage(new Page<>(current, size), wrapper);
        //判断第一页数据是否存在，不存在的则不限制时间段
        if (ArrayUtil.isEmpty(myPage.getRecords()) && current == 1) {
            QueryWrapper<VodDetail> wrapper2 = new QueryWrapper<>();
            vodTypes.forEach(item -> {
                wrapper2.or().eq("type_id", item.getTypeId());
            });
            //根据点击量来排序
            wrapper2.orderByDesc("vod_hits");
            return baseMapper.selectMapsPage(new Page<>(current, size), wrapper2);
        }
        return myPage;
    }

    @Override
    public List<Map<String, Object>> getVodNameMatchingItems(String searchText) {
        List<Map<String, Object>> items;
        if (StringUtils.hasText(searchText)) {
            List<VodDetail> vods = baseMapper.selectList(new Page<>(1, 10), new QueryWrapper<VodDetail>().like("vod_name", searchText));
            items = new ArrayList<>();
            vods.forEach(item -> {
                HashMap<String, Object> map = new HashMap<>();
                String vodName = item.getVodName();
                map.put("vodName", vodName);
                items.add(map);
            });
        } else {
            items = null;
        }
        return items;
    }

    @Override
    public Page<Map<String, Object>> fuzzySearchVodForSearchText(String searchText, String typeName, Integer current, Integer size) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        wrapper.like("vod_name", searchText);
        if (StringUtils.hasText(typeName)) {
            //查出动漫类型的id
            List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
            wrapper.and(w -> {
                vodTypes.forEach(item -> {
                    w.or().eq("type_id", item.getTypeId());
                });
            });
        }
        return baseMapper.selectMapsPage(new Page<>(current, size), wrapper);
    }

    @Override
    public List<VodDetail> getGuessYouLike(String vodClass, String area, String tag) {
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(area)) {
            wrapper.eq("vod_area", area);
        }
        if (StringUtils.hasText(vodClass)) {
            wrapper.like("vod_class", vodClass);
        }
        if (StringUtils.hasText(tag)) {
            //拆分标签
            String[] s = tag.split(",");
            wrapper.and(w -> {
                for (String value : s) {
                    w.or().like("vod_tag", value);
                }
            });
        }
        //排序
        wrapper.orderByDesc("vod_hits");
        //限制条数
        wrapper.last("limit 0,15");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<VodDetail> getHotVodByMaonthTypeArea(String typeName, String area, Integer size) {
        //查出类型的id
        List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(area)) {
            wrapper.like("vod_area", area);
        }
        wrapper.and(w -> {
            vodTypes.forEach(item -> {
                w.or().eq("type_id", item.getTypeId());
            });
        });
        //根据更新时间来排序
        wrapper.orderByDesc("vod_time");
        wrapper.last("limit 50");
        List<VodDetail> vodDetails = baseMapper.selectList(wrapper).stream().map(item -> {
            item.setVodPlayUrl("");
            return item;
        }).sorted(Comparator.comparingInt(VodDetail::getVodHits)).collect(Collectors.toList());
        //根据点击量排序
        //截取要求大小的集合
        List<VodDetail> subList = vodDetails.subList(0, size);
        return subList;
    }

    @Override
    public List<VodDetail> getVodsByWeekType(String week, String typeName, String area) {
        //查出类型的id
        List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(area)) {
            wrapper.like("vod_area", area);
        }
        wrapper.and(w -> {
            vodTypes.forEach(item -> {
                w.or().eq("type_id", item.getTypeId());
            });
        });
        List<VodDetail> vodDetails = baseMapper.selectList(wrapper);
        //筛选出以当前时间为中点的一个月内更新的,对应要求的星期
        long fifteenDays = 1296000000;
        long currentTimeMillis = Calendar.getInstance().getTimeInMillis();
        long firstFifteenDaysTimeMillis = currentTimeMillis - fifteenDays;
        long lastFifteenDaysTimeMillis = currentTimeMillis + fifteenDays;
        List<VodDetail> list = vodDetails
                .stream()
                .filter(item -> {
                    Long time = item.getVodTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    return firstFifteenDaysTimeMillis <= time && time <= lastFifteenDaysTimeMillis;
                })
                .filter(item -> week.equals(getDayOfWeek(item.getVodTime().toInstant(ZoneOffset.of("+8")).toEpochMilli())))
                .peek(item-> item.setVodPlayUrl(""))
                .collect(Collectors.toList());
        return list;
    }

    @Override
    public List<VodDetail> getHotVodMonthTypeAreaWithHitsMonth(String typeName, String area, Integer size) {
        //查出类型的id
        List<VodType> vodTypes = vodTypeService.getLikeName(typeName);
        QueryWrapper<VodDetail> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(area)) {
            wrapper.like("vod_area", area);
        }
        wrapper.and(w -> {
            vodTypes.forEach(item -> {
                w.or().eq("type_id", item.getTypeId());
            });
        });
        //根据月点击量来排序
        wrapper.orderByDesc("vod_hits_month");
        wrapper.last("limit 100");
        List<VodDetail> vodDetails = baseMapper.selectList(wrapper).stream().peek(item -> item.setVodPlayUrl("")).collect(Collectors.toList());
        //截取要求大小的集合
        List<VodDetail> subList = vodDetails.subList(0, size);
        return subList;
    }
}
